const express = require('express');
const router = express.Router();
const { pool } = require('../database');

// 获取所有医院列表
router.get('/', async (req, res) => {
  try {
    const [rows] = await pool.execute(`
      SELECT id, name, short_name, address, phone, logo, posters, work_days, 
             morning_work_time, afternoon_work_time, tags, 
             release_days, is_available, description, created_at, updated_at
      FROM hospitals 
      ORDER BY created_at DESC
    `);
    
    res.json({
      success: true,
      data: rows,
      message: '获取医院列表成功'
    });
  } catch (error) {
    console.error('获取医院列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医院列表失败',
      error: error.message
    });
  }
});

// 根据ID获取医院详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await pool.execute(`
      SELECT id, name, short_name, address, phone, logo, posters, work_days, 
             morning_work_time, afternoon_work_time, tags, 
             release_days, is_available, description, created_at, updated_at
      FROM hospitals 
      WHERE id = ?
    `, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '医院不存在'
      });
    }
    
    res.json({
      success: true,
      data: rows[0],
      message: '获取医院详情成功'
    });
  } catch (error) {
    console.error('获取医院详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医院详情失败',
      error: error.message
    });
  }
});

// 创建新医院
router.post('/', async (req, res) => {
  try {
    const {
      name, short_name, address, phone, logo, posters, work_days,
      morning_work_time, afternoon_work_time, tags,
      release_days, is_available, description
    } = req.body;
    
    // 验证必填字段
    if (!name || !short_name || !address) {
      return res.status(400).json({
        success: false,
        message: '医院名称、内部简称和地址为必填项'
      });
    }
    
    const [result] = await pool.execute(`
      INSERT INTO hospitals (name, short_name, address, phone, logo, posters, work_days,
                           morning_work_time, afternoon_work_time, tags,
                           release_days, is_available, description)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `, [
      name, short_name, address, phone || null, logo || null, posters || null, work_days || '1,2,3,4,5',
      morning_work_time || '8:00-12:00', afternoon_work_time || '14:00-17:00', tags || null,
      release_days || 7, is_available !== false, description || null
    ]);
    
    res.status(201).json({
      success: true,
      data: { id: result.insertId },
      message: '创建医院成功'
    });
  } catch (error) {
    console.error('创建医院失败:', error);
    res.status(500).json({
      success: false,
      message: '创建医院失败',
      error: error.message
    });
  }
});

// 更新医院信息
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      name, short_name, address, phone, logo, posters, work_days,
      morning_work_time, afternoon_work_time, tags,
      release_days, is_available, description
    } = req.body;
    
    // 检查医院是否存在
    const [existing] = await pool.execute('SELECT id FROM hospitals WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '医院不存在'
      });
    }
    
    await pool.execute(`
      UPDATE hospitals SET
        name = ?, short_name = ?, address = ?, phone = ?, logo = ?, posters = ?, work_days = ?,
        morning_work_time = ?, afternoon_work_time = ?, tags = ?,
        release_days = ?, is_available = ?, description = ?,
        updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `, [
      name, short_name, address, phone, logo, posters, work_days,
      morning_work_time, afternoon_work_time, tags,
      release_days, is_available, description, id
    ]);
    
    res.json({
      success: true,
      message: '更新医院信息成功'
    });
  } catch (error) {
    console.error('更新医院信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新医院信息失败',
      error: error.message
    });
  }
});

// 删除医院
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查医院是否存在
    const [existing] = await pool.execute('SELECT id FROM hospitals WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '医院不存在'
      });
    }
    
    // 删除医院（会级联删除相关数据）
    await pool.execute('DELETE FROM hospitals WHERE id = ?', [id]);
    
    res.json({
      success: true,
      message: '删除医院成功'
    });
  } catch (error) {
    console.error('删除医院失败:', error);
    res.status(500).json({
      success: false,
      message: '删除医院失败',
      error: error.message
    });
  }
});

// 获取医院可用状态
router.patch('/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { is_available } = req.body;
    
    if (typeof is_available !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: 'is_available 必须为布尔值'
      });
    }
    
    await pool.execute(
      'UPDATE hospitals SET is_available = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [is_available, id]
    );
    
    res.json({
      success: true,
      message: `医院已${is_available ? '启用' : '禁用'}`
    });
  } catch (error) {
    console.error('更新医院状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新医院状态失败',
      error: error.message
    });
  }
});

module.exports = router;
